package cn.socialcredits.activity.data.repo

import javax.inject.{Inject, Singleton}

import cn.socialcredits.activity.data.driver.MyDriver
import cn.socialcredits.activity.data.implicits.BSONImplicits._
import cn.socialcredits.activity.data.model.ActivityRegistration
import reactivemongo.bson.{BSONDocument, BSONObjectID}

import scala.concurrent.Future

@Singleton
class ActivityRegistrationRepo @Inject()(myDriver: MyDriver
                                          ) {

  import play.api.libs.concurrent.Execution.Implicits.defaultContext

  def insert(payload: ActivityRegistration): Future[ActivityRegistration] = {
    myDriver.collActivity.count(Some(BSONDocument("_id" -> payload.activityId))).flatMap {
      case 1 =>
        myDriver.collActivityRegistration.insert(payload).map { wr =>
          if (wr.n == 1) payload else throw new RuntimeException("insert error: " + payload)
        }
      case _ =>
        Future.failed(new RuntimeException(s"activity: ${payload.activityId} not exists"))
    }
  }

  def findOneById(id: BSONObjectID): Future[Option[ActivityRegistration]] = {
    myDriver.collActivityRegistration.find(BSONDocument("_id" -> id)).one[ActivityRegistration]
  }
}

